package com.qjdchina.sku.biz.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.qjdchina.sku.dao.mapper.SkuProductMapper;
import com.qjdchina.sku.model.ProductCount;
import com.qjdchina.sku.model.vo.CategoryStatisticsVO;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qjdchina.commons.enums.IsDeleted;
import com.qjdchina.commons.result.Result;
import com.qjdchina.sku.biz.CategoryManager;
import com.qjdchina.sku.dao.mapper.CategoryBrandMapper;
import com.qjdchina.sku.dao.mapper.CategoryMapper;
import com.qjdchina.sku.model.Category;
import com.qjdchina.sku.model.CategoryBrand;
import com.qjdchina.sku.model.query.CategoryQueryVO;
import com.qjdchina.sku.service.enums.SkuResultCode;

/**
 * Created by fankiwu on 2016/11/22.
 */
@Service
public class CategoryManagerImpl implements CategoryManager {

	private static final Logger LOGGER = LoggerFactory.getLogger(CategoryManager.class);

	@Autowired
	private CategoryMapper categoryMapper;

	@Autowired
	private CategoryBrandMapper categoryBrandMapper;

	@Autowired
	private SkuProductMapper skuProductMapper;

	/**
	 * 根据公司获取所有根品类 shenpingfeng 2017年2月16日
	 * 
	 * @return
	 */
	@Override
	public Result<List<Category>> getAllRootCategoryByCompany(Integer skuCompanyId) {

		List<Category> allRootCategory = categoryMapper.getAllRootCategoryWhereStatement(skuCompanyId);

		return new Result<List<Category>>(allRootCategory);
	}

	/**
	 * 获取所有根品类 shenpingfeng 2017年2月16日
	 * 
	 * @return
	 */
	@Override
	public Result<List<Category>> getAllRootCategory() {

		List<Category> allRootCategory = categoryMapper.getAllRootCategory();

		return new Result<List<Category>>(allRootCategory);
	}

	/**
	 * 根据父类ID获取子类 shenpingfeng 2017年2月16日
	 * 
	 * @param parentId
	 * @param skuCompanyId
	 * @return
	 */
	@Override
	public Result<List<Category>> getChildCategorysByCompany(Integer parentId, Integer skuCompanyId) {

		List<Category> categories = categoryMapper.getChildCategoryWhereStatement(skuCompanyId, parentId);
		
		return new Result<List<Category>>(categories);
	}

	/**
	 * 根据父类ID获取子类 shenpingfeng 2017年2月16日
	 * 
	 * @param id
	 * @return
	 */
	@Override
	public Result<List<Category>> getChildCategorys(Integer id) {
		List<Category> allChildCategory = categoryMapper.getAllChildCategory(id);
		return new Result<List<Category>>(allChildCategory);
	}
	/**
	 * 根据parentId查询 shenpingfeng 2016年12月9日
	 * 
	 * @param parentId
	 * @return
	 */
	@Override
	public Result<List<Category>> getCagegorysByParentId(Integer parentId) {
		if (parentId == null) {
			return new Result<List<Category>>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		List<Category> categories = new ArrayList<Category>();
		while(parentId != null){
			Category category = categoryMapper.selectByPrimaryKey(parentId);
			parentId = category.getParentId();
			categories.add(category);
		}
		return new Result<List<Category>>(categories);
	}

	/**
	 * 根据Id查询 shenpingfeng 2016年12月9日
	 * 
	 * @param id
	 * @return
	 */
	@Override
	public Result<Category> getCagegorysById(Integer id) {
		if (id == null) {
			return new Result<Category>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		Category category = categoryMapper.selectByPrimaryKey(id);
		if (category == null) {
			return new Result<Category>(SkuResultCode.DATA_NOT_EXIST);
		}
		return new Result<Category>(category);
	}

	/**
	 * 创建品类信息 shenpingfeng 2016年12月29日
	 * 
	 * @param category
	 * @return
	 */
	@Override
	public Result<String> createCategory(Category category) {
		if (category == null) {
			return new Result<String>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		category.setGmtCreated(new Date());
		category.setGmtModified(new Date());
		category.setIsDeleted(IsDeleted.NO.getValue());
		String code = category.getCode();
		if (StringUtils.isBlank(code)) {
			code = UUID.randomUUID().toString();
		}
		category.setCode(code);
		// 校验code的唯一 TODO
		int row = categoryMapper.insertSelective(category);
		if (row == 0) {
			return new Result<String>(SkuResultCode.ADD_FAIL);
		}
		return new Result<String>(category.getCode());
	}
	/**
	 * 创建品类品牌关联 shenpingfeng 2017年1月11日
	 * 
	 * @param categoryBrand
	 * @return
	 */
	@Override
	public Result<String> createCategoryBrand(CategoryBrand categoryBrand) {
		if (categoryBrand == null) {
			return new Result<String>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		categoryBrand.setGmtCreated(new Date());
		categoryBrand.setGmtModified(new Date());
		categoryBrand.setIsDeleted(IsDeleted.NO.getValue());
		int row = categoryBrandMapper.insertSelective(categoryBrand);
		if (row == 0) {
			return new Result<String>(SkuResultCode.ADD_FAIL);
		}
		return new Result<String>(categoryBrand.getOperateId());
	}

	/**
	 * 更新品类 shenpingfeng 2017年2月9日
	 * 
	 * @param category
	 * @return
	 */
	@Override
	public Result<String> update(Category category) {
		if (category == null || category.getId() == null) {
			return new Result<String>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}

		int row = categoryMapper.updateByPrimaryKeySelective(category);
		if (row == 0) {
			return new Result<String>(SkuResultCode.UPDATE_FAIL);
		}
		return new Result<String>(category.getCode());
	}

	/**
	 * 根据品牌Id获取品类 shenpingfeng 2017年2月9日
	 * 
	 * @param skuBrandId
	 * @return
	 */
	@Override
	public Result<List<Category>> getCategoryBySkuBrandId(Integer skuBrandId) {
		if (skuBrandId == null) {
			return new Result<List<Category>>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		List<Category> categories = categoryMapper.selectBySkuBrandId(skuBrandId);
		return new Result<List<Category>>(categories);
	}
	
	/**
	 * 根据条件查询category
	 * shenpingfeng
	 * 2017年4月12日
	 * @param categoryQueryVO
	 * @return
	 */
	@Override
	public Result<Category> getCategoryWhereStatement(CategoryQueryVO categoryQueryVO) {
		if (categoryQueryVO == null) {
			return new Result<Category>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		Map<String, Object> params = convertCategoryQueryVOToMap(categoryQueryVO);
		Category category = categoryMapper.selectCategoryWhereStatement(params);
		return new Result<Category>(category);
	}

	private Map<String, Object> convertCategoryQueryVOToMap(CategoryQueryVO queryVO) {
		Map<String, Object> params = new HashMap<String, Object>();

		params.put("code", queryVO.getCode());

		return params;

	}

	@Override
	public Result<List<CategoryStatisticsVO>> categoryProductStatistical(List<Integer> parentIds) {
		//获取已录入表头品类
		List<Category> itemCategoryList = categoryMapper.getAllItemCategory();
		//获取一级品类
		List<Category> categoryList = categoryMapper.selectByIds(parentIds);

		//获取二级品类
		List<Category> firstCategoryList = categoryMapper.getChildCategoryByParentIds(parentIds);
		List<Integer> firstCategoryIds = new ArrayList<>();
		for (Category category : firstCategoryList) {
			firstCategoryIds.add(category.getId());
		}

		//三级品类计算
		List<Category> secondCategoryList = categoryMapper.getChildCategoryByParentIds(firstCategoryIds);
		List<Integer> secondCategoryIds = new ArrayList<>();
		for (Category category : secondCategoryList) {
			secondCategoryIds.add(category.getId());
		}
		//三级品类部品数量
		List<ProductCount> secondProductCount = skuProductMapper.selectCountByCategoryId(secondCategoryIds);
		Map<Integer, Integer> secondCategoryCountMap = new HashMap<>();
		for(ProductCount productCount : secondProductCount){
			secondCategoryCountMap.put(productCount.getSkuCategoryId(), productCount.getNumber());
		}

		List<CategoryStatisticsVO> secondCategoryStatisticsVOList = new ArrayList<>();
		for (Category category : secondCategoryList) {
			for (Category itemCategory : itemCategoryList) {
				if (itemCategory.getId().equals(category.getId())) {
					CategoryStatisticsVO categoryStatisticsVO = convertCategoryStatisticsVO(itemCategory, secondCategoryCountMap);
					secondCategoryStatisticsVOList.add(categoryStatisticsVO);
				}
			}
		}

		//四级品类计算
		List<Category> thirdCategoryList = categoryMapper.getChildCategoryByParentIds(secondCategoryIds);
		List<Integer> thirdCategoryIds = new ArrayList<>();
		for (Category category : thirdCategoryList) {
			thirdCategoryIds.add(category.getId());
		}
		//四级品类部品数量
		List<ProductCount> thirdProductCount = skuProductMapper.selectCountByCategoryId(thirdCategoryIds);
		Map<Integer, Integer> thirdCategoryCountMap = new HashMap<>();
		for(ProductCount productCount : thirdProductCount){
			thirdCategoryCountMap.put(productCount.getSkuCategoryId(), productCount.getNumber());
		}

		for (CategoryStatisticsVO categoryStatisticsVO : secondCategoryStatisticsVOList) {
			List<CategoryStatisticsVO> thirdCategoryStatisticsVOList = new ArrayList<>();
			for (Category itemCategory : itemCategoryList) {
				if (itemCategory.getParentId().equals(categoryStatisticsVO.getCategoryId())) {
					CategoryStatisticsVO thirdCategoryStatisticsVO = convertCategoryStatisticsVO(itemCategory, thirdCategoryCountMap);
					thirdCategoryStatisticsVOList.add(thirdCategoryStatisticsVO);
				}
			}
			categoryStatisticsVO.setCategoryStatisticsVOList(thirdCategoryStatisticsVOList);
		}

		//二级品类计算
		List<CategoryStatisticsVO> firstCategoryStatisticsVOList = getParentCategoryStatisticsVOList(firstCategoryList,
				secondCategoryStatisticsVOList);
		//一级品类计算
		List<CategoryStatisticsVO> rootCategoryStatisticsVOList = getParentCategoryStatisticsVOList(categoryList,
				firstCategoryStatisticsVOList);

		return new Result<List<CategoryStatisticsVO>>(rootCategoryStatisticsVOList);
	}

	/**
	 * 封装CategoryStatisticsVO
	 *
	 * @param category
	 * @param categoryCountMap
	 * @return
	 */
	private CategoryStatisticsVO convertCategoryStatisticsVO(Category category, Map<Integer, Integer> categoryCountMap) {
		CategoryStatisticsVO categoryStatisticsVO = new CategoryStatisticsVO();
		categoryStatisticsVO.setCategoryId(category.getId());
		categoryStatisticsVO.setParentId(category.getParentId());
		categoryStatisticsVO.setCategoryName(category.getLabel());
		categoryStatisticsVO.setProductNum(categoryCountMap.get(category.getId()));

		return categoryStatisticsVO;
	}

	/**
	 * 封装父类品类统计
	 *
	 * @param categoryList
	 * @param categoryStatisticsVOList
	 * @return
	 */
	private List<CategoryStatisticsVO> getParentCategoryStatisticsVOList(List<Category> categoryList, List<CategoryStatisticsVO>
			categoryStatisticsVOList) {
		List<CategoryStatisticsVO> parentCategoryStatisticsVOList = new ArrayList<>();

		for (Category category : categoryList) {
			CategoryStatisticsVO newCategoryStatisticsVO = new CategoryStatisticsVO();
			newCategoryStatisticsVO.setCategoryId(category.getId());
			newCategoryStatisticsVO.setParentId(category.getParentId());
			newCategoryStatisticsVO.setCategoryName(category.getLabel());
			List<CategoryStatisticsVO> childCategoryStatisticsVOList = new ArrayList<>();
			Integer count = 0;
			for (CategoryStatisticsVO categoryStatisticsVO : categoryStatisticsVOList) {
				if (category.getId().equals(categoryStatisticsVO.getParentId())) {
					childCategoryStatisticsVOList.add(categoryStatisticsVO);
					if (categoryStatisticsVO.getProductNum() != null) {
						count += categoryStatisticsVO.getProductNum();
					}
				}
			}
			newCategoryStatisticsVO.setCategoryStatisticsVOList(childCategoryStatisticsVOList);
			newCategoryStatisticsVO.setProductNum(count);
			parentCategoryStatisticsVOList.add(newCategoryStatisticsVO);
		}

		return parentCategoryStatisticsVOList;
	}
}
